<template>
  <div>
    <!-- 面包屑导航中传入是否显示弹出层的数据 使用语法糖 .sync这样的简写 -->
    <!-- v-bind:属性名称 和 $emit('update:属性名称')  v-on:update:属性名称 -->
    <xw-pagenav :visible.sync="visible" />
    <!-- 表格展示 -->
    <el-card class="box-card">
      <el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border>
        <el-table-column prop="username" label="账号" width="200"> </el-table-column>
        <el-table-column prop="showname" label="角色" width="200"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="prop">
            <el-button type="primary" size="mini">修改</el-button>
            <el-button type="danger" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br />
      <el-pagination layout="prev, pager, next" :page-size="pageSize" :total="total" @current-change="handleChange">
      </el-pagination>
    </el-card>
    <!-- 添加弹出层 -->
    <xw-dialog :title="title" :visible.sync="visible" :addHandler="addHandler">
      <el-form slot="add" :model="formData" status-icon :rules="createRules()" ref="ruleForm" label-width="100px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="formData.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="pid">
          <el-select v-model="formData.role" placeholder="请选择对应角色">
            <el-option label="管理者" value="1"> </el-option>
            <el-option label="编辑者" value="2"> </el-option>
            <el-option label="开发者" value="3"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </xw-dialog>
  </div>
</template>

<script>
import { checkUserApi, addUserApi, userListApi } from '@/api/userApi'
export default {
  data() {
    return {
      title: '添加用户',
      visible: false,
      tableData: [],
      pageSize: 10,
      total: 1000,
      formData: {
        username: '',
        nickname: '',
        password: '',
        role: '2'
      }
    }
  },
  mounted() {
    this.handleChange()
  },
  methods: {
    // 分页
    async handleChange(page = 1) {
      let ret = await userListApi(page)
      this.tableData = ret.data
    },
    addHandler() {
      // 触发前端的表单项验证
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // 如果验证通过，则进行网络请求完成数据的处理
          const ret = await addUserApi(this.formData)
          if (ret.code == 0) {
            this.$message({
              type: 'success',
              duration: 1500,
              message: '添加成功',
              onClose: () => {
                this.visible = false
              }
            })
          }
        } else {
          this.$message({
            type: 'error',
            duration: 1500,
            message: '验证失败'
          })
        }
      })
    },
    createRules() {
      return {
        username: [
          { required: true, message: '账号必须填写' },
          {
            validator: (rule, value, callback) => {
              if (/^\d|\s+/.test(value)) {
                return callback(new Error('账号中不能以数字或空格'))
              }
              return callback()
            }
          },
          // 账号在数据库中是不能重名,进行ajax请求验证 -- 异步返回Promise
          {
            validator: (rule, value) => {
              return new Promise((resolve, reject) => {
                checkUserApi(value)
                  .then(ret => {
                    if (ret.code == 0) {
                      resolve('')
                    } else {
                      reject('账号已经存在')
                    }
                  })
                  .catch(() => reject('网络异常'))
              })
            }
          }
        ],
        password: [{ required: true, message: '密码必须填写', trigger: 'blur' }]
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
